﻿using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Xioa_UI.DataOrigin;

namespace Xioa_UI.Controls;

public class XioaTcpBorder : ContentControl
{
    #region 依赖属性定义

    public Visibility VisibilityHeader
    {
        get { return (Visibility)GetValue(VisibilityHeaderProperty); }
        set { SetValue(VisibilityHeaderProperty, value); }
    }

    public static readonly DependencyProperty VisibilityHeaderProperty =
        DependencyProperty.Register("VisibilityHeader", typeof(Visibility), typeof(XioaTcpBorder));

    public double HeaderFontSize
    {
        get { return (double)GetValue(HeaderFontSizeProperty); }
        set { SetValue(HeaderFontSizeProperty, value); }
    }

    public static readonly DependencyProperty HeaderFontSizeProperty =
        DependencyProperty.Register("HeaderFontSize", typeof(double), typeof(XioaTcpBorder));


    public string Ip
    {
        get { return (string)GetValue(IpProperty); }
        set { SetValue(IpProperty, value); }
    }

    public static readonly DependencyProperty IpProperty =
        DependencyProperty.Register("Ip", typeof(string), typeof(XioaTcpBorder));


    public int Port
    {
        get { return (int)GetValue(PortProperty); }
        set { SetValue(PortProperty, value); }
    }

    public static readonly DependencyProperty PortProperty =
        DependencyProperty.Register("Port", typeof(int), typeof(XioaTcpBorder));

    public XioaTcpBorder()
    {

    }
    public XioaTcpData XioatcpDatqa = new XioaTcpData();

    #endregion

    #region private property

    private Socket? socketCore { get; set; } = null;
    private byte[] buffer { get; set; } = new byte[2048];

    #endregion

    #region Method

    public void Send(string content)
    {
        if (socketCore is null)
            throw new Exception("Socket Need Initialize ! Please Used This Initialize Method !");
        byte[]? send = null;
        send = Encoding.ASCII.GetBytes(content);
        socketCore?.Send(send);
    }

    public bool Initialize(string name)
    {
        try
        {
            XioaTcpDataContent.AcceptContent.TryGetValue(name, out var value);
            if (value is not null)
                return false;
            socketCore?.Close();
            socketCore = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socketCore.Connect(System.Net.IPAddress.Parse(Ip), Port);
            socketCore.BeginReceive(buffer, 0, 2048, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socketCore);

            XioaTcpDataContent.AcceptContent.Add(name, XioatcpDatqa);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    private void ReceiveCallBack(IAsyncResult ar)
    {
        try
        {
            int length = socketCore!.EndReceive(ar);
            socketCore.BeginReceive(buffer, 0, 2048, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socketCore);

            if (length == 0) return;

            byte[] data = new byte[length];
            Array.Copy(buffer, 0, data, 0, length);
            Task.Run(new Action(() =>
            {
                var msg = string.Empty;
                msg = Encoding.ASCII.GetString(data);
                XioatcpDatqa.AcceptContent = msg;
            }));
        }
        catch (ObjectDisposedException)
        {
        }
        catch (Exception ex)
        {
            Task.Run(new Action(() => { XioatcpDatqa.AcceptContent = "服务器断开连接"; }));
        }
    }

    public void CloseServer()
    {
        this.socketCore?.Close();
    }

    #endregion
}


public class XioaTcpDataContent
{
    public static Dictionary<string, XioaTcpData> AcceptContent { get; set; } = new Dictionary<string, XioaTcpData>();
    public static string GetValue(string token)
    {
        try
        {
            AcceptContent.TryGetValue(token, out XioaTcpData? data);
            if (data == null) throw new Exception();
            return data?.AcceptContent;
        }
        catch (Exception)
        {

            return "Not Found Name Data";
        }

    }
}